package com.linjinp.study.缓存;

import lombok.Getter;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 并发实现缓存
 * @Author: linjinp
 * @Date: 2021/1/11 10:33
 */
public class Memoizer<A, V> implements Computable<A, V> {

    @Getter
    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();

    private final Computable<A, V> c;

    public Memoizer(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws InterruptedException, ExecutionException {
        while (true) {
            Future<V> f = cache.get(arg);
            // 验证缓存是否存在
            if (f == null) {
                Callable<V> eval = new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return c.compute(arg);
                    }
                };
                FutureTask<V> ft = new FutureTask<>(eval);
                // 线程安全的如果为空则添加操作
                f = cache.putIfAbsent(arg, ft);
                // 基于上一步操作，只会有一个线程的 f 有值
                if (f == null) {
                    f = ft;
                    // 调用 c.compute
                    ft.run();
                }
            }
            return f.get();
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Computable bigIntegerFun = new ExpensiveFunction();
        Memoizer m = new Memoizer(bigIntegerFun);
        m.compute("111111");
        m.compute("2222");
        m.compute("999");
        m.getCache().values().stream().forEach(item -> {
            try {
                System.out.println(((Future) item).get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}

interface Computable<A, V> {
    V compute(A arg) throws InterruptedException, ExecutionException;
}

class ExpensiveFunction implements Computable<String, BigInteger> {

    @Override
    public BigInteger compute(String arg) {
        return new BigInteger(arg);
    }
}